﻿using System;
using Microsoft.Office.Core;
using TShooter.TfsWord.Xml;
using WordDocument = Microsoft.Office.Interop.Word._Document;

namespace TShooter.TfsWord.TeamFoundation
{
    public class Document
    {
        #region Constructors and member variables

        private readonly DocumentInfo _DocInfo;
        private readonly WordDocument _WordDoc;

        public Document(WordDocument doc)
        {
            _WordDoc = doc;
            _DocInfo = LoadDocInfo(doc);
        }

        #endregion

        #region Properties

        public DateTime LastConnection
        {
            get { return _DocInfo.ConnectionInfo.LastConnection; }
            set { _DocInfo.ConnectionInfo.LastConnection = value; }
        }

        public ConnectionStatus LastStatus
        {
            get { return _DocInfo.ConnectionInfo.LastStatus; }
            set { _DocInfo.ConnectionInfo.LastStatus = value; }
        }

        public string TeamProject
        {
            get { return _DocInfo.ConnectionInfo.TeamProject; }
            set { _DocInfo.ConnectionInfo.TeamProject = value; }
        }

        public Uri TeamProjectCollectionUri
        {
            get { return _DocInfo.ConnectionInfo.TeamProjectCollectionUri; }
            set { _DocInfo.ConnectionInfo.TeamProjectCollectionUri = value; }
        }

        #endregion

        private static DocumentInfo LoadDocInfo(WordDocument doc)
        {
            CustomXMLParts parts = doc.CustomXMLParts.SelectByNamespace(Consts.XmlNamespace);

            if ((parts != null) && (parts.Count > 0))
            {
                string partXml = parts[1].XML;
                return DocumentInfo.FromXml(partXml);
            }

            return new DocumentInfo();
        }

        private void SaveDocInfo()
        {
            CustomXMLParts parts = _WordDoc.CustomXMLParts.SelectByNamespace(Consts.XmlNamespace);

            if ((parts == null) || (parts.Count <= 0))
            {
                _WordDoc.CustomXMLParts.Add(_DocInfo.ToXml(), null);
            }
            else
            {
                parts[1].LoadXML(_DocInfo.ToXml());
            }
        }

        private void UpdateXmlPart()
        {
        }
    }
}